package com.zhihuichongcheng.application.net;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;

import com.smartlib.cmnObject.constant.CmnConstant;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.LogUtil;
import com.smartlib.cmnObject.util.StringUtil;
import com.zhihuichongcheng.application.ui.mine.LoginActivity;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

//import com.android.volley.AuthFailureError;
//import com.android.volley.RequestQueue;
//import com.android.volley.VolleyError;
//import com.android.volley.toolbox.StringRequest;
//import com.android.volley.toolbox.Volley;


/**
 * @author：hww
 * @date:2016/4/23
 * @description:<请求的管理类>
 */
public class HttpManager {
    private static HttpManager mHttpManager;
    long progress = 0;
    private String TAG = "http";
//    private RequestQueue mRequestQueue;

    private OkHttpClient mOkHttpClient;
    /***
     * 超时时间
     */
    private int CONNECT_TIME_OUT = 30;

    private int READ_TIME_OUT = 30;

    private Context mContext;

    private HttpManager(Context context) {
        mContext = context;
        mOkHttpClient = new OkHttpClient();
        mOkHttpClient.newBuilder().connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS).build();
    }


    public static HttpManager getInstance(Context context) {
        if (mHttpManager == null) {
            mHttpManager = new HttpManager(context);
        }
        return mHttpManager;
    }

    /***
     * get  请求
     *
     * @param url 请求的url
     */
    public void get(String url, final HttpCallback httpCallback, HashMap<String, String> param) {
        url = getParams(url, param);

        final Handler handler = new Handler(mContext.getMainLooper());
        Request request = new Request.Builder().url(url).build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        httpCallback.onFailure("");
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String value = response.body().string();
                            LogUtil.logI(value);
                            BaseRep rep = GsonUtil.praseFromStringToBean(value, BaseRep.class);
                            if (rep != null) {
                                int code = rep.getStatus();
                                String data = rep.getData().toString();
                                httpCallback.onSuccess(code, data, "");
                            } else {
                                httpCallback.onFailure("");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    /***
     * @param url
     * @param param
     * @return
     */
    public static String getParams(String url, HashMap<String, String> param) {
        String getparams = "";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            getparams = getparams + entry.getKey() + "=" + entry.getValue() + "&";
        }
        getparams = getparams.substring(0, getparams.length() - 1);
        url = url + "?" + getparams;
        LogUtil.logI("url:" + url);
        return url;
    }

    public void post(String url, final HttpCallback httpCallback, HashMap<String, String> param) {
        final Handler handler = new Handler(mContext.getMainLooper());
        FormBody.Builder builder = new FormBody.Builder();
        Iterator iter = param.keySet().iterator();
        String testurl = getParams(url, param);
        String token = "";
        String requestUrl = url;
        if (param.containsKey("token")) {
            token = param.get("token").toString();
            requestUrl += "?token=" + token;
        }
        LogUtil.logI(testurl);
        while (iter.hasNext()) {
            String key = iter.next().toString();
            String value = param.get(key);
            if (!StringUtil.isEmpty(value)) {
                if (!key.equals("token")) {
                    builder.add(key, value);
                    requestUrl += "&" + key + "=" + value;
                }
            } else if (key.equals("taskId")) {
                builder.add(key, value);
                requestUrl += "&" + key + "=" + value;
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build()).header("token", token)
                .build();
        LogUtil.logI("--API--" + requestUrl);
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        LogUtil.logD(e.getMessage());
                        httpCallback.onFailure("");
                    }
                }, 500);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String value = response.body().string();
                LogUtil.logI(value);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            int status = 0;
                            String data = "";
                            String msg = "";
                            JSONObject object = new JSONObject(value);
                            if (object.has("status")) {
                                status = object.getInt("status");
                            }
                            msg = object.getString("message");
                            if (status == CmnConstant.HTTP_SUCCESS) {
                                if (object.has("data")) {
                                    data = object.getString("data");
                                }
                            } else if (status == CmnConstant.TOKEN_TIME_OUT) {
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                mContext.startActivity(intent);
                            } else {
                                msg = object.getString("message");
                            }
                            httpCallback.onSuccess(status, data, msg);
                        } catch (Exception e) {
                            httpCallback.onFailure("");
                            e.printStackTrace();
                        }
                    }
                }, 500);
            }
        });

    }

    public void downLoad(String url, String path) {
        final File file = new File(path);
        if (file.exists()) {
            return;
        }
        final byte[] arr = new byte[4 * 1024];
        OkHttpClient client = new OkHttpClient();
        try {
            Request request = new Request.Builder().url(url).build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = response.body().byteStream();
                    FileOutputStream fos = new FileOutputStream(file, true);
//                        int n = inputStream.read(arr);
                    int len = 0;
                    while ((len = is.read(arr)) != -1) {
                        fos.write(arr, 0, len);
                    }
                    fos.flush();
                    fos.close();
                    is.close();
                }

            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void downLoad(String url, String path, final DownLoadCallback downLoadCallback) {
        final Handler handler = new Handler(mContext.getMainLooper());
        final File file = new File(path);
        final byte[] arr = new byte[4 * 1024];
        OkHttpClient client = new OkHttpClient();
        try {
            Request request = new Request.Builder().url(url).build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            downLoadCallback.onFailure("");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = response.body().byteStream();
                    is.skip(file.length());
                    final long total = is.available();
                    FileOutputStream fos = new FileOutputStream(file, true);
                    int len = 0;
                    while ((len = is.read(arr)) != -1) {
                        fos.write(arr, 0, len);
                        progress = progress + len;
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                downLoadCallback.progress(total, progress);
                            }
                        });
                    }
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            downLoadCallback.onSuccess("");
                        }
                    });
                    fos.flush();
                    fos.close();
                    is.close();
                }

            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doDelete(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).delete().build();
        execute(request);
//        LogUtil.logD(execute(request));
    }

    public static void execute(final Request request) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                try {
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        LogUtil.logD("fengdjeiyiyi" + response.body().string());
//                        return response.body().string();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }
}
